<script lang="ts" setup>
import {Diff2HtmlUI} from "diff2html/lib/ui/js/diff2html-ui";
import {onMounted, ref} from "vue";
import {Diff2HtmlUIConfig} from "diff2html/lib/ui/js/diff2html-ui-base";
import {createPatch} from "diff";
import {useRoute} from "vue-router";
import {basename} from "@tauri-apps/api/path";
import {getContent} from "../utils/file";
import {cvsGetTagFile} from "../utils/cvs";
import {ElLoading} from "element-plus";

const configuration: Diff2HtmlUIConfig = {
  drawFileList: false,
  matching: 'lines',
  highlight: true,
  outputFormat: 'side-by-side',
  fileListStartVisible: false,
  fileListToggle: false,
  fileContentToggle: false,
  stickyFileHeaders: true,
};

const route = useRoute();
const filename = ref('')
const baseVersionTag = ref('') // 基线版本TAG

onMounted(async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '  加载差异中...',
    background: 'rgba(0, 0, 0, 0)', 
  })
  const filePath = route.query.file as string;
  filename.value = await basename(filePath)
  const tag = route.query.tag as string;
  baseVersionTag.value = tag
  if (!tag) {
    console.error('No base tag found');
    return;
  }
  try {
    const content = await getContent(filePath)
    const tagContent = await cvsGetTagFile(filePath, tag)
    loadDiffUI(filename.value, tagContent, content)
  } finally {
    loading.close()
  }
})

const loadDiffUI = (filename: string, oldStr: string, newStr: string) => {
  const targetElement = document.getElementById('diff');
  if (targetElement) {
    const diffString = createPatch(
        filename,
        oldStr,
        newStr,
        undefined,
        undefined,
        {
          context: 10,
          ignoreWhitespace: true,
          ignoreNewlineAtEof: true,
        }
    );
    const diff2htmlUi = new Diff2HtmlUI(targetElement, diffString, configuration);
    diff2htmlUi.draw();
    diff2htmlUi.highlightCode();
  }
}

</script>

<template>
  <div class="flex flex-col h-screen">
    <div class="flex flex-col justify-between bg-gray-100 pt-2">
      <div class="flex flex-row">
        <div class="diff-tag">{{ baseVersionTag }}</div>
        <div class="diff-tag">Local</div>
      </div>
    </div>
    <div id="diff"></div>
  </div>
</template>

<!--suppress CssUnusedSymbol -->
<style>
@import 'diff2html/bundles/css/diff2html.min.css';

#diff {
  width: 100%;
  flex: 1;
  background-color: #f8f9fa;
  border-radius: 5px;
}

.diff-tag {
  @apply w-[50%] ml-2 text-sm select-none;
}

.d2h-info {
  display: none;
}

.d2h-file-header {
  display: none;
}

.d2h-wrapper {
  height: 100%;
}

.d2h-file-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.d2h-files-diff {
  flex: 1;
}

</style>